#include "core/engine.h"
#include "core/kernel.h"
#include "core/logger.h"
#include "core/renderwindow.h"
#include "core/procinput.h"
#include "core/application.h"

namespace engine {
		
	namespace core {
			
		Engine::Engine() {
			Logger::setDefaultPath("/home/kazade/Desktop/mt-engine/logs");
			Logger::getLogger("kernel")->setLevel(LL_DEBUG);
			Logger::getLogger("window")->setLevel(LL_DEBUG);
		}
		
		Engine::~Engine() {
			
		}
		
		int Engine::startEngine() {
			loadBaseProcesses();
			m_Kernel->run();					
			return 0;
		}
		
		bool Engine::loadBaseProcesses() {
			Logger::getLogger("engine")->info("Loading base processes");
			m_Kernel->addProcess(shared_ptr<Process>(new ProcInput(m_Kernel)));
			
			return true;
		}
		
		void Engine::stopEngine() {
			if (m_Window)
				m_Window->destroy();
		}
		
		
		bool Engine::initialize(bool createWindow, const string& title) {
			Logger::getLogger("engine")->debug("Initializing the engine");
			
			m_Kernel = shared_ptr<Kernel> (new Kernel());
			m_Kernel->setParentEngine(this);
			
			m_SceneManager = shared_ptr<SceneManager> (new SceneManager());
			
			if (createWindow) {
				if (!createRenderWindow(640, 480, false, title)) {
					Logger::getLogger("engine")->error("Unable to create a window");
					return false;
				}
			}
			
			return true;
		}
		
		shared_ptr<RenderWindow> Engine::createRenderWindow(uint width, 
															uint height, 
															bool fullscreen,
															const string& title) {
			if (m_Window) {
				m_Window->destroy();
			}
			
			m_Window = shared_ptr<RenderWindow> (new RenderWindow());
			if (!m_Window->create(width, height, 0, 0, title, fullscreen, 16))
				m_Window.reset();
				
			return m_Window;
			
		}
				
		void Engine::registerApplication(shared_ptr<Application> app) {
			m_Kernel->addProcess(boost::dynamic_pointer_cast<Process>(app));
		}
		
		shared_ptr<Kernel> Engine::getKernel() {
			return m_Kernel;
		}
	}
}
